package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author AzureSky_X
 * @Date 2020/11/16 21:46
 * @Version 1.0
 */

public class BaseController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action =request.getParameter("action");
        //接下来用户模块会有很多的功能
        //比如：action=login
        //action=logout.....
        //每有一个action，我们都要做一次else if判断（程序的健壮性和可拓展性不足）
        //思考？action的参数就是我们的方法名，拿到action，我们就拿到了方法名
        //通过方法名，我们可以利用反射得到方法对象，方法对象他有一个invoke（）方法
        Class c1=this.getClass();

        //通过方法名，拿到具体的方法对象
        try {
            Method method=c1.getMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            String resultStr= (String) method.invoke(this,request,response);//方法执行，并且拿到返回值
            //转发+重定向+json
            String realPath=request.getContextPath();
            if (resultStr.startsWith("forward")){
                String[] split=resultStr.split(":");
                request.getRequestDispatcher(split[1]).forward(request,response);
            }else if (resultStr.startsWith("redirect")){
                String[] split=resultStr.split(":");
                response.sendRedirect(realPath+"/"+split[1]);
            }else {
                response.getWriter().print(resultStr);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
